<template>
  <el-card class="w-full pt-[5px] pb0">
    <el-radio-group v-model="searchForm.reviewPlanState" @change="handleSearch">
      <el-radio-button :label="`全部(${countMap.total})`" value="" />
      <el-radio-button :label="`未启动(${countMap.notStart})`" value="notStart" />
      <el-radio-button :label="`评审中(${countMap.review})`" value="review" />
      <el-radio-button :label="`已停止(${countMap.stop})`" value="stop" />
    </el-radio-group>
    <el-form :model="searchForm" class="mt-[20px]" label-width="110px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="评审计划名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="评审计划名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0">
            <CommonDateSelect
              placeholder="开始日期"
              v-model:startTime="searchForm.beginDate1"
              v-model:endTime="searchForm.beginDate2"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="评审方案" prop="reviewSchemeIds">
            <CustomTreeSelect
              placeholder="评审方案"
              :isFetch="false"
              :dataList="psfaList"
              v-model="searchForm.reviewSchemeIds"
              valueKey="id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0">
            <CommonDateSelect
              placeholder="结束日期"
              v-model:startTime="searchForm.endDate1"
              v-model:endTime="searchForm.endDate2"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="psfaModalVisible = true">
        <el-icon class="mr-[5px]"><Document /></el-icon>
        评审方案
      </el-button>
      <el-button @click="handleMessage">
        <el-icon class="mr-[5px]"><Bell /></el-icon>
        评审通知
      </el-button>
      <el-button @click="handleDelSelect">
        <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
        删除
      </el-button>
    </div>
    <el-table :data="tableData" class="w-full" stripe ref="tableRef" v-loading="loading">
      <el-table-column type="selection" width="40" />
      <el-table-column label="评审计划名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.planId)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="评审方案" width="150">
        <template #default="{ row }">
          <CommonLabel :dataList="psfaList" :value="row.reviewSchemeId" valueKey="id" />
        </template>
      </el-table-column>
      <el-table-column label="开始日期" width="120">
        <template #default="{ row }">
          <DateLabel :value="row.beginDate" />
        </template>
      </el-table-column>
      <el-table-column label="结束日期" width="120">
        <template #default="{ row }">
          <DateLabel :value="row.endDate" />
        </template>
      </el-table-column>
      <el-table-column label="评审项目数（项）" width="90">
        <template #default="{ row }">
          <el-link type="primary" @click="toPsxmPage(row.infoId)">{{ row.schoolPass }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="评审专家数（人）" width="90">
        <template #default="{ row }">
          <el-link type="primary" @click="toExpertPage(row.infoId, row.planId)">{{
            row.expertNum
          }}</el-link>
        </template>
      </el-table-column>
      <!-- 点击批准立项数（项）进入评审项目页面立项状态默认传2 -->
      <el-table-column label="批准立项数（项）" width="90">
        <template #default="{ row }">
          <el-link type="primary" @click="toPsxmPage(row.infoId, 2)">{{ row.lixiangNum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="评审状态" width="80">
        <template #default="{ row }">
          <CommonLabel :dataList="planStatusList" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" plain @click="handleEdit(row.planId)">
            编辑
          </el-button>
          <el-button type="primary" size="small" plain @click="handleChange(row)">
            {{ row.status == "review" ? "结束" : "启动" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @save-success="handleSearch" />
  <ViewModal ref="viewModalRef" />
  <PsfaModal v-model="psfaModalVisible" />
  <PsMessageModal ref="psMessageModalRef" />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import CommonDateSelect from "@/views/project/components/CommonDateSelect.vue";
import { getList, delRecords, changeState, getCount } from "@/api/project/xj/xmps";
import { getList as getFaList } from "@/api/project/xj/psfasz";
import ViewModal from "./components/ViewModal.vue";
import EditModal from "./components/EditModal.vue";
import PsfaModal from "./components/PsfaModal.vue";
import PsMessageModal from "./components/PsMessageModal.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import DateLabel from "@/views/project/components/DateLabel.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import { ElMessage } from "element-plus";
import useCommonFetch from "@/hooks/useCommonFetch";
import { useRouter } from "vue-router";
const router = useRouter();
const planStatusList = useCommonFetch("评审计划状态"); //评审状态;
const searchFormOpen = ref(false);
const editModalRef = ref();
const viewModalRef = ref();
const psMessageModalRef = ref();
const psfaModalVisible = ref(false);
const searchFormRef = ref();
const tableRef = ref();
const psfaList = ref([]); //评审方案列表
const countMap = ref({
  total: 0,
  notStart: 0,
  review: 0,
  stop: 0,
});
const searchForm = ref({
  reviewPlanState: "",
  name: "",
  beginDate1: "",
  beginDate2: "",
  endDate1: "",
  endDate2: "",
  reviewSchemeIds: [],
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNum: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击编辑
const handleEdit = (id) => {
  editModalRef.value.edit(id);
};
//点击名称查看评审计划
const handleShow = (id) => {
  viewModalRef.value.view(id);
};
//点击评审项目数跳转至评审项目页面
const toPsxmPage = (id, status = "") => {
  router.push(`/project/xj/psxm/index?id=${id}&status=${status}`);
};
//点击评审专家数跳转至评审专家页面
const toExpertPage = (id, planId) => {
  router.push(`/project/xj/expert/index?id=${id}&planId=${planId}`);
};
//评审通知
const handleMessage = () => {
  psMessageModalRef.value.view();
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.planId);
  handleDelete(delRecords, ids);
};
//获取评审方案列表
const getPsfaList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
  };
  try {
    const res = await getFaList(params);
    psfaList.value = res.rows;
  } catch (error) {
    console.log(error);
  }
};
//启动或停止
const handleChange = async (row) => {
  const params = {
    planId: row.planId,
    state: row.status == "review" ? "stop" : "review",
  };
  try {
    const res = await changeState(params);
    if (res.code == 200) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      handleSearch();
    }
  } catch (error) {
    console.log(error);
  }
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
    reviewPlanState: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      notStart: 0,
      review: 0,
      stop: 0,
    };
    let totalCount = 0;
    res.data.forEach((item) => {
      countMap.value[item.name] = item.count;
      totalCount += item.count;
    });
    countMap.value.total = totalCount;
  } catch (error) {
    console.log(error);
  }
}
onMounted(() => {
  getPsfaList();
});
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.beginDate1 = "";
  searchForm.value.beginDate2 = "";
  searchForm.value.endDate1 = "";
  searchForm.value.endDate2 = "";
  handleSearch();
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
